<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>GatewatWorker</title>
    <style>
        body {
            margin: 0;
        }

        ul {
            list-style-type: none;
            margin-block-start: 0;
            margin-block-end: 0;
            padding-inline-start: 0;
        }

        ul:nth-child(2) li img {
            vertical-align: bottom;
        }

        div {
            display: none;
            padding: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,.2);
            border: 1px solid #d9d9d9;
        }

        div ul {
            width: 372px;
        }

        div ul li {
            border: 1px solid #e8e8e8;
            padding: 4px 2px;
            display: inline-block;
            height: 22px;
            width: 26px;
            text-align: center;
            margin: -1px 0 0 -1px;
        }

        div ul li img {
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1></h1>
    <ul></ul>
    <div></div>
    <form>
        <input type="text" value="" />
        <img class="face-default" style="vertical-align: middle;" src="/gatewayworker/public/static/face/default.png" alt="表情" title="表情" />
        <input type="file" accept="image/*" />
    </form>
    <script>
        window.onload = function () {
            scrollTopBottom();
            generateFace();
            window.user_id = '{:input("get.user_id")}';
            window.to_id = '{:input("get.to_id")}';
            // 实例化 WebSocket 实例
            var Socket = new WebSocket('ws://127.0.0.1:8282');
            // 连接成功
            Socket.onopen = function () {
                console.log('已建立连接');
                send();
                upload();
            }

            // 接收数据
            Socket.onmessage = function (res) {
                console.log(res);
                var data = JSON.parse(res.data);
                switch (data.type) {
                    case 'init':
                        getMessage();
                        Socket.send(JSON.stringify({type: 'bindUid', user_id: window.user_id}));
                        getNickName();
                        Socket.send(JSON.stringify({type: 'online', user_id: window.user_id, to_id: window.to_id}));
                        break;
                    case 'online':
                        document.querySelector('h1').innerText = data.status ? '在线' : '离线';
                        break;
                    case 'text':
                        if (data.user_id == window.to_id) {
                            var ul = document.querySelector('ul'),
                                input = document.querySelector('input'),
                                li = document.createElement('li');
                            li.innerHTML = repFace(data.content);
                            ul.appendChild(li);
                            input.value = '';
                            scrollTopBottom();
                        }
                        break;
                    case 'image':
                        if (data.user_id == window.to_id) {
                            var ul = document.querySelector('ul'),
                                li = document.createElement('li'),
                                image = new Image();
                            image.src = '/gatewayworker/public/uploads/image/' + data.content;
                            image.onload = function () {
                                var img = document.createElement('img');
                                img.src = '/gatewayworker/public/uploads/image/' + data.content;
                                img.style = 'max-height: 100px;';
                                img.alt = img.title = data.content;
                                li.appendChild(img);
                                ul.appendChild(li);
                                scrollTopBottom();
                            }
                        }
                        break;
                    case 'save':
                        document.querySelector('h1').innerText = data.is_read ? '在线' : '离线';
                        save(data);
                    default:
                        break;
                }
            }

            // 关闭连接
            Socket.onclose = function () {
                console.log('连接已关闭');
            }

            // 连接错误
            Socket.onerror = function () {
                console.log('连接错误');
            }

            // 滚动最底部
            function scrollTopBottom() {
                setTimeout(function () {
                    var html = document.querySelector('html');
                    html.scrollTop = html.scrollHeight;
                }, 1);
            }

            // 生成表情
            function generateFace() {
                var faceDefault = document.querySelector('.face-default'),
                    div = document.querySelector('div'),
                    input = document.querySelector('input'),
                    ul = document.createElement('ul');
                faceDefault.onclick = function (e) {
                    e.stopPropagation();
                    div.style.display = getComputedStyle(div, null).display === 'none' ? 'inline-block' : 'none';
                }
                div.onclick = function (e) {
                    e.stopPropagation();
                }
                document.onclick = function () {
                    div.style.display = 'none';
                }
                for (var i = 0; i < 72; i++) {
                    var li = document.createElement('li'),
                        img = document.createElement('img');
                    img.src = '/gatewayworker/public/static/face/' + i + '.gif';
                    img.alt = img.title = img.name = '[face' + i + ']';
                    img.onclick = function (e) {
                        input.value += this.name;
                    }
                    li.appendChild(img);
                    ul.appendChild(li);
                }
                div.appendChild(ul);
            }

            // 获取消息
            function getMessage() {
                fetch('{:Url("index/Index/getMessage", "user_id=" . input("get.user_id") . "&to_id=" . input("get.to_id"))}').then(response => response.json()).then(data => {
                    var ul = document.querySelector('ul');
                    for (var i = 0; i < data.length; i++) {
                        var li = document.createElement('li');
                        if (data[i].user_id == '{:input("get.user_id")}') li.style.textAlign = 'right';
                        switch (data[i].type) {
                            case 'text':
                                li.innerHTML = repFace(data[i].content);
                                break;
                            case 'image':
                                var img = document.createElement('img');
                                img.style.maxHeight = '100px';
                                img.src = '/gatewayworker/public/uploads/image/' + data[i].content;
                                img.alt = img.title = data[i].content;
                                li.appendChild(img);
                                break;
                        }
                        ul.appendChild(li);
                    }
                })
            }

            // 匹配表情
            function repFace(str) {
                str = str.replace(/\</g, '&lt;');
                str = str.replace(/\>/g, '&gt;');
                str = str.replace(/\n/g, '<br />');
                str = str.replace(/\[face([0-9]*)\]/g, '<img src="/gatewayworker/public/static/face/$1.gif" />');
                return str;
            }

            // 发送
            function send() {
                var form = document.querySelector('form'),
                    input = document.querySelector('input'),
                    ul = document.querySelector('ul');
                form.onsubmit = function (e) {
                    e.preventDefault();
                    if (input.value === '') return;
                    Socket.send(JSON.stringify({content: input.value, content_type: 'text', type: 'say', user_id: window.user_id, to_id: window.to_id}));
                    var li = document.createElement('li');
                    li.innerHTML = repFace(input.value);
                    li.style.textAlign = 'right';
                    ul.appendChild(li);
                    input.value = '';
                    scrollTopBottom();
                }
            }

            // 上传
            function upload() {
                var file = document.getElementsByTagName('input')[1];
                file.onchange = function () {
                    var formData = new FormData();
                    if (file.files[0].type !== undefined && file.files[0].type.indexOf('image') === -1) {
                        file.outerHTML = file.outerHTML;
                        upload();
                        return;
                    }
                    formData.append('file', file.files[0]);
                    fetch('{:Url("index/Index/upload")}', {
                        method: 'POST',
                        body: formData
                    }).then(response => response.text()).then(data => {
                        Socket.send(JSON.stringify({content: data, content_type: 'image', type: 'say', user_id: window.user_id, to_id: window.to_id}));
                        var ul = document.querySelector('ul'),
                            li = document.createElement('li'),
                            image = new Image();
                            image.src = '/gatewayworker/public/uploads/image/' + data;
                        image.onload = function () {
                            var img = document.createElement('img');
                            img.src = '/gatewayworker/public/uploads/image/' + data;
                            img.style = 'max-height: 100px;';
                            img.alt = img.title = data;
                            li.style.textAlign = 'right';
                            li.appendChild(img);
                            ul.appendChild(li);
                            scrollTopBottom();
                        }
                    })
                    file.outerHTML = file.outerHTML;
                    upload();
                }
            }

            // 获取昵称
            function getNickName() {
                fetch('{:Url("index/Index/getNickName", "id=" . input("get.to_id"))}').then(response => response.text()).then(data => document.querySelector('title').innerText = '与' + data + '聊天中...');
            }
            
            // 保存聊天记录
            function save(data) {
                fetch('{:Url("index/Index/save")}', {
                    method: 'POST',
                    headers: {'Content-type': 'application/json'},
                    body: JSON.stringify({user_id: data.user_id, to_id: data.to_id, content: data.content, type: data.content_type, create_time: data.time, is_read: data.is_read})
                })
            }
        }
    </script>
</body>

</html>